/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbShm.cpp			*/
/********************************************************/

#include "GlbShm.h"

namespace GlbIpc
{

CGlbShm::CGlbShm()
{
	m_pShm = NULL;
}

CGlbShm::~CGlbShm()
{
	m_pShm = NULL;
}

int CGlbShm::GlbShmLock()
{
	return shmctl(CGlbIpc::m_iIpc, SHM_LOCK, NULL);
}

int CGlbShm::GlbShmUnlock()
{
	return shmctl(CGlbIpc::m_iIpc, SHM_UNLOCK, NULL);
}

void* CGlbShm::GlbShmGetShm()
{
	return m_pShm;
}

void CGlbShm::GlbShmReset(ULONG ulSize)
{
	if (NULL != m_pShm) {
		memset(m_pShm, '\0', ulSize);
	}

	return;
}

void CGlbShm::GlbShmDetach()
{
	if (NULL != m_pShm) {
		shmdt(m_pShm);
	}

	return;
}

void* CGlbShm::GlbShmAttach()
{
	void* pReturn = NULL;

	if (GLB_FAILURE != CGlbIpc::m_iIpc) {
		pReturn = m_pShm = shmat(CGlbIpc::m_iIpc, NULL, 0);
		if ((void*)GLB_FAILURE == pReturn) {
			GLB_ERROR("%s\n", strerror(errno));
		}
	}

	return pReturn;
}

int CGlbShm::GlbIpcCreate(key_t iKey, ULONG ulSize)
{
	int iReturn = GLB_SUCCESS;

	CGlbIpc::m_iIpc = shmget(iKey, ulSize, IPC_CREAT | 0777);
	if (GLB_FAILURE == CGlbIpc::m_iIpc) {
		GLB_ERROR("%s\n", strerror(errno));
		iReturn = GLB_FAILURE;
	}

	if (NULL == GlbShmAttach()) {
		iReturn = GLB_FAILURE;
	}

	return iReturn;
}

int CGlbShm::GlbIpcDelete()
{
	return shmctl(CGlbIpc::m_iIpc, IPC_RMID, NULL);
}

} /* GlbIpc */
